<?php
/**
 * 中原协和基因检测服务销售
 * Created by PhpStorm.
 * User: denh
 * Date: 16/10/9
 * Time: 下午2:35
 */
class ZyxhController extends BaseController {

    Const PRODUCT_PRICE = 0.1;
    Const PRODUCT_NAME = '儿童基因检测';
    Const ORDER_NOTICE = '欢迎您购买中源协和儿童基因检测产品，如支付未成功，请您复制网址 %s'; //下单通知
    Const ORDER_PAYED_NOTICE = '您已成功购买中源协和儿童基因检测产品，客服电话：4006688298，支付详情：%s'; //下单支付成功通知
    Const GETMONEYED_NOTICE = '您好！我们已经受理您的提现申请，到账时间以银行转账时间为准，请留意您的银行消息通知。'; //提现成功通知
    Const MAIL_TO = '408470495@qq.com'; #babydoctorsbd@daishuyifu.com
    Const MAIL_TITLE = '有新订单啦-爱贝儿医';

    public $data = array();

    function __construct($m = DEFAULT_CONTROLLER, $a = DEFAULT_METHOD) {
        parent::__construct($m, $a);
        if (!$this->getUserInfo() and !in_array($a, array('wxGzhUrl', 'wxGzhLogin', 'payStatus', 'orderDetail', 'getMoneyCallBack'))) {
            $get = $_GET;
            unset($get['m']);
            unset($get['a']);
            header("Location:". $this->wxGzhUrl($m, $a, $get));
        }
        require_once ROOT_PATH . 'bs/bs.automation.php';
    }

    #商品展示页
    function index() {
        $shareId = $this->request('shareId', '');
        $userInfo = $this->getUserInfo();
        logger()->logInfo("userInfo:" . var_export($userInfo, true));
        $fid = $userInfo['id'];

        $doUser = new DoZyxh_user();
        $doUser->loadById($fid);

        $doOrder = new DoZyxh_order();
        $doOrder->set_uid($userInfo['id']);
        if ($doOrder->where($doOrder->data)->row()) {
            $this->data['button_name'] = '我的订单';
        } else {
            $this->data['button_name'] = '立即购买';
        }

        $this->data['order'] = $doOrder;
        $this->data['button_url'] = $this->url('zyxh', 'order', array('orderId' => $doOrder->get_id(), 'shareId' => $shareId));

        $doNews = new DoZyxh_news();
        $doShare = new DoZyxh_share();
        $doShare->loadById($shareId);

        if ($doShare->get_fid()) {
            $doShareUser = new DoZyxh_user();
            $doShareUser->loadById($doShare->get_fid());


        }


        $ffid = $doShare->get_fid() ? $doShare->get_fid() : 0;
        $shareIdNew = $this->share($ffid);

        //分享被查看添加通知
        if($shareId && ($fid != $doShare->get_fid())) {
            $doNews->set_uid($doShare->get_fid());
            $doNews->set_content($doUser->get_nickname().'查看了您的分享');
            $doNews->set_type('1');
            $doNews->set_orderId($doOrder->get_id());
            $doNews->set_operatorId($fid);
            $doNews->save();
        }

        $newsList = $doNews->leftJoin($doUser,'b','a.operatorId=b.id')
            ->fields("a.content,a.id,a.money,date_format(a.createTime,'%Y-%m-%d') as createTime,b.headimgurl")
            ->where(array('uid'=>$fid))
            ->orderby('a.type desc,a.id desc')
            ->rows();
        $shareUrl = $this->url('zyxh','index',array('shareId'=>$shareIdNew));
        $getMoneyUrl = $this->url('zyxh', 'getMoney');
        $incomeRuleUrl = $this->url('zyxh', 'incomeRule');
        $canTakeMoney = $this->canTakeMoney();
        require_once $this->template;

    }

    #下订单|更新订单|我的订单
    function order() {
        $orderId = $this->request('orderId', '');
        $shareId = $this->request('shareId','');
        $doOrder = new DoZyxh_order();
        if ($doOrder->loadById($orderId)) {
            if ($doOrder->get_pay_status() == 1) {
                $this->redirect('zyxh', 'orderDetail', array('orderId' => $orderId));
            } else {
                require_once $this->template;
            }
        } else {
            require_once $this->template;
        }

    }

    #订单详情
    function orderDetail() {
        $orderId = $this->request('orderId', '');
        if (!$orderId) {
            $this->redirect('zyxh', 'index');
        }
        $doOrder = new DoZyxh_order();
        $doOrder->loadById($orderId);
        require_once $this->template;
    }

    #下订单
    function order_post() {
        $shareId = $this->request('shareId', 0);
        $userInfo = $this->getUserInfo();
        $doShare = new DoZyxh_share();
        if ($doShare->loadById($shareId)) {
            $fid = $doShare->get_fid();
            $ffid = $doShare->get_ffid();
        } else {
            $fid = 0;
            $ffid = 0;
        }

        if ($fid and $ffid) {
            $fid_money = self::PRODUCT_PRICE * 0.16;
            $ffid_money = self::PRODUCT_PRICE * 0.04;
        } else if($fid and !$ffid) {
            $fid_money = self::PRODUCT_PRICE * 0.2;
            $ffid_money = 0;
        } else {
            $fid_money = 0;
            $ffid_money = 0;
        }

        #通过自己分享的页面购买，不计入提成
        if ($fid == $userInfo['id']) {
            $fid = 0;
            $fid_money = 0;
        }
        if ($ffid == $userInfo['id']) {
            $ffid = 0;
            $ffid_money = 0;
        }

        $orderId = $this->request('orderId', '');
        $orderNum = date("YmdHis") . rand(1000,9999);
        $babyName = $this->request('babyName', '', true);
        $birthday = $this->request('birthday', '', true);

        $name = $this->request('name', '', true);
        $sex = $this->request('sex', '', true);
        $identityCardNum = $this->request('identityCardNum', '', true);
        $email = $this->request('email', '', true);
        $phone = $this->request('phone', '', true);
        $phone_checkCode = $this->request('phone_checkCode', '', true);
        $address = $this->request('address', '', true);
        $receiptName = $this->request('receiptName', '', true);

        if ($phone_checkCode != $_SESSION['phone_checkCode']) {
            $this->jsonOutPut(-1, '验证码错误');
        }

        $doOrder = new DoZyxh_order();
        if ($orderId) {
            $doOrder->loadById($orderId);
        } else {
            $doOrder->set_orderNum($orderNum);
        }
        $doOrder->set_uid($userInfo['id']);
        $doOrder->set_babyName($babyName);
        $doOrder->set_birthday($birthday);
        $doOrder->set_name($name);
        $doOrder->set_sex($sex);
        $doOrder->set_identityCardNum($identityCardNum);
        $doOrder->set_email($email);
        $doOrder->set_phone($phone);
        $doOrder->set_address($address);
        $doOrder->set_receiptName($receiptName);
        $doOrder->set_money(self::PRODUCT_PRICE);
        $doOrder->set_shareId($shareId);
        $doOrder->set_fid($fid);
        $doOrder->set_ffid($ffid);
        $doOrder->set_fid_money($fid_money);
        $doOrder->set_ffid_money($ffid_money);
        if (!$doOrder->save()) {
            $this->jsonOutPut(-1, '订单提交失败');
        }

        #调用获取支付参数接口
        $this->load_hprose(WXPAY_BASE_URL);
        $param = array(
            'orderNum' => $doOrder->get_orderNum(),
            'productName' => self::PRODUCT_NAME,
            'openId' => $_SESSION['zyxh']['openid'],
            'money' => self::PRODUCT_PRICE * 100,
            'fid' => $fid,
            'ffid' => $ffid,
            'fid_money' => floor($fid_money * 100),
            'ffid_money' => floor($ffid_money * 100),
            'callBackUrl' => $this->url('zyxh', 'payStatus', array('orderId' => $doOrder->get_id())),
            'clientIp' => Tools::getIP(),
            'nonce' => rand(1000, 9999),
        );
        ksort($param);

        $param_sign = $param;
        foreach ($param_sign as $k => $v) {
            $param_sign[$k] = $k .'='. $v;
        }

        logger()->logInfo("origin_sign". implode('#', $param_sign) . '#'. self::SECRET_KEY);
        $sign = md5( implode('#', $param_sign) . '#'. self::SECRET_KEY ); //签名
        $re = self::$hproseHttpClient->AppPayController_zyxhCreatePay(
            $param['orderNum'],
            $param['productName'],
            $param['openId'],
            $param['money'],
            $param['fid'],
            $param['ffid'],
            $param['fid_money'],
            $param['ffid_money'],
            $param['callBackUrl'],
            $param['clientIp'],
            $param['nonce'],
            $sign
        );

        if ($re->code != 0) {
            $this->jsonOutPut(-1, '支付参数获取失败');
        }

        if (!$orderId) {
            $orderUrl = $this->url('zyxh', 'order', array('orderId' => $doOrder->get_id()));
            $MsgContent = sprintf(self::ORDER_NOTICE, $orderUrl);
            $automation = new automation();
            $automation->send_text_messages($MsgContent, $phone);
        }

        $this->jsonOutPut(0, 'ok', array('pay' => $re->obj, 'orderId' => $doOrder->get_id()));
    }

    #发送验证码
    function checkCode() {
        $phone = $this->request('phone', '', true);
        $code = rand(1000, 9999);
        $_SESSION['phone_checkCode'] = $code;

        $content = $code. "仅本次有效，请勿转发或告知他人。";
        $automation = new automation();
        $automation->send_text_messages($content, $phone);
        $this->jsonOutPut(0,'ok');
    }

    #支付成功回调
    function payStatus() {
        $orderId = $this->request('orderId', '', true);
        $sign = $this->request('sign', '', true);

        $request = $_REQUEST;
        unset($request['sign']);
        ksort($request);
        foreach($request as $k => $v) {
            $request[$k] = $k . '=' . $v;
        }
        $sign_check = md5( implode('#', $request) . '#' . self::SECRET_KEY );

        if ($sign != $sign_check) {
            $this->jsonOutPut(-1, '签名不正确');
        }

        $doOrder = new DoZyxh_order();
        $doOrder->set_id($orderId);
        $doOrder->set_pay_status(1);
        $doOrder->set_payTime(date('Y-m-d H:i:s'));
        if (!$doOrder->save()) {
            $this->jsonOutPut(-1, '订单状态更新失败');
        }

        #发送通知短信
        $doOrder->loadById($orderId);
        $orderUrl = $this->url('zyxh', 'orderDetail', array('orderId' => $orderId));
        $MsgContent = sprintf(self::ORDER_PAYED_NOTICE, $orderUrl);
        $automation = new automation();
        $automation->send_text_messages($MsgContent, $doOrder->get_phone());

        #发邮件通知中原协和
        $email_content = $this->email_template($doOrder);
        logger()->logInfo("==email_content==: ".$email_content);
        $this->sendMail(self::MAIL_TO, '中原协和', self::MAIL_TITLE, $email_content);

        #给相关分享人发购买消息
        $this->sendBuyNews($doOrder);

        $this->jsonOutPut(0, 'ok');
    }

    #给相关分享人发购买消息
    function sendBuyNews(DoZyxh_order $doOrder) {
        $fid = $doOrder->get_fid();
        $ffid = $doOrder->get_ffid();
        $myId = $doOrder->get_uid();

        $doNew = new DoZyxh_news();
        $doNew->set_operatorId($myId);
        $doNew->set_type('2');
        $doNew->set_orderId($doOrder->get_id());

        if ($fid != 0) {
            #查寻被通知用户姓名
            $doUser = new DoZyxh_user();
            $doUser->row($fid);

            $doNew->set_uid($fid);
            $doNew->set_money($doOrder->get_fid_money());
            $doNew->set_content($doOrder->get_name() . '已购买');
            $res1 = $doNew->insert();
            if ($ffid != 0) {
                $doNew->set_uid($ffid);
                $doNew->set_money($doOrder->get_ffid_money());
                $doNew->set_content($doOrder->get_name().'通过'.$doUser->get_nickname().'已购买');
                $res2 = $doNew->insert();
            }
        }

        $doNew->set_uid($myId);
        $doNew->set_money($doOrder->get_money());
        $doNew->set_content($doOrder->get_name().'已购买');
        $res = $doNew->insert();
    }

    #提现
    function getMoney() {
        $canTakeMoney = $this->canTakeMoney();
        require_once $this->template;
    }

    #返回可提前金额
    protected function canTakeMoney() {
        $this->load_hprose(WXPAY_BASE_URL);
        $userInfo = $this->getUserInfo();
        $uid = $userInfo['id'];
        $nonce = rand(1000, 9999);
        $sign = md5('nonce='.$nonce.'#uid='.$uid.'#'.self::SECRET_KEY);
        $re = self::$hproseHttpClient->AppPayController_zyxhUserMoney($uid, $nonce, $sign);

        logger()->logInfo("==canTakeMoney==:". var_export($re, true));
        if ($re->code == 0) {
            $canTakeMoney = $re->obj->totalMoney - $re->obj->totalWithdrawCashing;
            $canTakeMoney = $canTakeMoney / 100;
        } else {
            $canTakeMoney = 0;
        }

        return $canTakeMoney;
    }

    #提现
    function getMoney_post() {
        $this->load_hprose(WXPAY_BASE_URL);

        $bankName = $this->request('bankName', '', true);
        $bankOpenAddr = $this->request('bankOpenAddr', '', true);
        $bankAccountId = $this->request('bankAccountId', '', true);
        $bankAccountName = $this->request('bankAccountName', '', true);
        $money = $this->canTakeMoney();
        $phone = $this->request('phone', '', true);
        $phone_checkCode = $this->request('phone_checkCode', '', true);

        if ($_SESSION['phone_checkCode'] != $phone_checkCode) {
            $this->jsonOutPut(-1, '验证码不正确');
        }

        $userInfo = $this->getUserInfo();
        $param = array(
            'uid' => $userInfo['id'],
            'bankName' => $bankName,
            'bankOpenAddr' => $bankOpenAddr,
            'bankAccountId' => $bankAccountId,
            'bankAccountName' => $bankAccountName,
            'money' => $money * 100,
            'phone' => $phone,
            'callBackUrl' => $this->url('zyxh', 'getMoneyCallBack', array('uid' => $userInfo['id'], 'phone' => $phone)),
            'nonce' => rand(1000, 9999),
        );

        ksort($param);
        $param_sign = $param;
        foreach ($param_sign as $k => $v) {
            $param_sign[$k] = $k .'='. $v;
        }
        $sign = md5( implode('#', $param_sign) . '#'. self::SECRET_KEY ); //签名

        $re = self::$hproseHttpClient->AppPayController_zyxhWithdrawCash(
            $param['uid'],   //用户ID
            $param['bankName'],   //银行名称
            $param['bankOpenAddr'],   //开户地址
            $param['bankAccountId'],   //银行账号
            $param['bankAccountName'],   //银行账号名称
            $param['money'],   //提现金额 单位:分
            $param['phone'],   //手机号
            $param['callBackUrl'],   //String回调地址
            $param['nonce'],   //随机数
            $sign
        );

        logger()->logInfo("==getMoney_post==". var_export($re, true));

        if ($re->code != 0) {
            $this->jsonOutPut(-1, $re->msg);
        }
        $this->jsonOutPut(0, 'ok');
    }

    #体现成功回调
    function getMoneyCallBack() {
        $uid = $this->request('uid', '', true);
        $phone = $this->request('phone', '', true);
        $sign = $this->request('sign', '', true);

        $request = $_REQUEST;
        unset($request['sign']);
        ksort($request);
        foreach($request as $k => $v) {
            $request[$k] = $k . '=' . $v;
        }
        $sign_check = md5( implode('#', $request) . '#' . self::SECRET_KEY );

        if ($sign != $sign_check) {
            $this->jsonOutPut(-1, '签名不正确');
        }

        $MsgContent = self::GETMONEYED_NOTICE;

        require_once ROOT_PATH . 'bs/bs.automation.php';
        $automation = new automation();
        $automation->send_text_messages($MsgContent, $phone);

        $userInfo = $this->getUserInfo();
        $wxNews = C信息中心::get实列根据公众号OpenId();
        $wxNews->ff发送文本消息($MsgContent, $userInfo['openid']);
        $this->jsonOutPut(0, 'ok');
    }

    #记录商品的被分享的记录
    function share($ffid=0) {
        $userInfo = $this->getUserInfo();
        $fid = $userInfo['id'];

        $doShare = new DoZyxh_share();
        $doShare->set_fid($fid);
        $doShare->set_ffid($ffid);
        if ($doShare->save()) {
            return $doShare->get_id();
        }
        return 0;
    }

    #记录商品的被分享状态修改
    function shareUp() {
        $shareId = $this->request('shareId','',true);

        $doShare = new DoZyxh_share();
        $doShare->set_id($shareId);
        $doShare->set_status(1);
        if ($doShare->save()) {
            $this->jsonOutPut(0, 'ok', array('shareId' => $shareId,'status'=>$doShare->get_status()));
        } else {
            $this->jsonOutPut(-1, '修改分享状态失败');
        }
    }

    #收入规则
    function incomeRule() {
        require_once $this->template;
    }

    function getUserInfo() {
        //$_SESSION['zyxh']['id']=4;
        if ($_SESSION['zyxh']['id']) {
            return $_SESSION['zyxh'];
        }
        return false;
    }

    function email_template(DoZyxh_order $doOrder) {
        ob_start();
        require_once $this->template('zyxh', 'email_template');
        $content = ob_get_contents();
        ob_end_clean();
        return $content;
    }

    /**
     * @param $to
     * @param $toName
     * @param $title
     * @param $content
     * @return bool
     * @throws Exception
     * @throws phpmailerException
     *
     */
    function sendMail($to, $toName, $title, $content) {
        require_once ROOT_PATH .'sdk/PHPMailer-master/class.phpmailer.php';
        require_once ROOT_PATH .'sdk/PHPMailer-master/class.smtp.php';

        $from_mail = 'services@cyyz-health.com';
        $from_user_name = '爱贝儿医';
        $password = 'Cyyz@123456';

        $mail  = new PHPMailer();
        $mail->CharSet    ="UTF-8";                 //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置为 UTF-8
        $mail->IsSMTP();                            // 设定使用SMTP服务
        $mail->SMTPAuth   = true;                   // 启用 SMTP 验证功能
        $mail->SMTPSecure = "ssl";                  // SMTP 安全协议
        $mail->Host       = "smtp.exmail.qq.com";       // SMTP 服务器
        $mail->Port       = 465;                    // SMTP服务器的端口号
        $mail->Username   = $from_mail;  // SMTP服务器用户名
        $mail->Password   = $password;        // SMTP服务器密码
        $mail->SetFrom($from_mail, $from_user_name);    // 设置发件人地址和名称
        $mail->AddReplyTo($from_mail, $from_user_name); // 设置邮件回复人地址和名称

        $mail->Subject    = $title;                     // 设置邮件标题
        $mail->AltBody    = "为了查看该邮件，请切换到支持 HTML 的邮件客户端"; // 可选项，向下兼容考虑

        $mail->MsgHTML($content);                         // 设置邮件内容
        $mail->AddAddress($to, $toName);
        //$mail->AddAttachment("images/phpmailer.gif"); // 附件
        if(!$mail->Send()) {
           // echo "发送失败：" . $mail->ErrorInfo;
            logger()->logInfo("发送失败：" . $mail->ErrorInfo);
            return false;
        } else {
           return true;
        }
    }

    function wxGzhUrl($m, $a, $parm) {
        $doGzh = new DoPublic_serv_accounts();
        $doGzh->set_id(G_SERV_ID);
        $doGzh->where($doGzh->data)->row();

        $parm = json_encode($parm);

        $url = Tools::url('zyxh', 'wxGzhLogin', array('parm' => $parm));
        $url = urlencode($url);
        $appId = $doGzh->get_app_id();
        $state = sprintf("%s_%s", $m, $a);
        $pg = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appId}&redirect_uri={$url}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
        return $pg;
    }

    #获取微信用户openid
    function wxGzhLogin() {
        $code = $this->request('code', true);
        $state = $this->request('state', true); #页面
        $parm = $this->request('parm');
        $parm = json_decode($parm, true);
        $shareId = isset($parm['shareId']) ? $parm['shareId'] : 0;
        $fid = 0;
        if ($shareId) {
            $doShare = new DoZyxh_share();
            $doShare->loadById($shareId);
            $fid = $doShare->get_fid();
        }

        list($m, $a) = explode('_', $state, 2);
        $doGzh = new DoPublic_serv_accounts();
        $doGzh->set_id(G_SERV_ID);
        $doGzh->where($doGzh->data)->row();

        $appId = $doGzh->get_app_id();
        $secret = $doGzh->get_AppSecret();
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appId}&secret={$secret}&code={$code}&grant_type=authorization_code";
        $re = self::$tools->curl_get_contents($url);
        $obj = json_decode($re);

        if ($obj) {
            $openId = $obj->openid;
            $access_token = $obj->access_token;

            $doUser = new DoZyxh_user();
            if ($doUser->where("openid = '$openId'")->row()) {
                $_SESSION['zyxh'] = $doUser->data;
            } else {
                $_SESSION['zyxh']['openid'] = $openId;
                $url_userInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openId&lang=zh_CN";
                $re_userInfo = self::$tools->curl_get_contents($url_userInfo);
                $obj_userInfo = json_decode($re_userInfo);
                if (!$obj_userInfo) {
                    $this->errorPage('error 001');
                }
                $doUser->set_openid($obj_userInfo->openid);
                $doUser->set_city($obj_userInfo->city);
                $doUser->set_country($obj_userInfo->country);
                $doUser->set_headimgurl($obj_userInfo->headimgurl);
                $doUser->set_province($obj_userInfo->province);
                $doUser->set_nickname($obj_userInfo->nickname);
                $doUser->set_sex($obj_userInfo->sex);
                $doUser->set_fid($fid);
                if (!$doUser->save()) {
                    $this->errorPage('error 002');
                }
                $_SESSION['zyxh'] = $doUser->data;
            }
            $this->redirect($m, $a, $parm);
        } else {
            Logger::getInstance()->logInfo("[ZyxhController|wxGzhLogin]OpenId get failed!");
        }
    }
}